package com.cloud.rou.im.connection.server;

import com.cloud.rou.im.connection.container.connection.UserIdAttributeKey;
import com.cloud.rou.im.connection.container.session.Session;
import com.cloud.rou.im.connection.service.ConnectorService;
import com.cloud.rou.im.msg.*;
import com.cloud.rou.im.core.process.AbstractIMProcessor;
import com.cloud.rou.im.protocol.cmd.Cmd;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-10-24 17:18
 */
@Slf4j
public class LoginHandler extends SimpleChannelInboundHandler<Cmd> {

    private ConnectorService service = new ConnectorService();


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 注册信息
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Cmd msg) throws Exception {
        ClientMsgProcessor clientMsgProcessor = new ClientMsgProcessor();
        clientMsgProcessor.process(ctx,msg.getMsg());
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Long userId = ctx.channel().attr(UserIdAttributeKey.USER_ID).get();
        Session.destroyedByUserId(userId);
    }

    class ClientMsgProcessor extends AbstractIMProcessor<Class<? extends Msg>,Msg> {
        @Override
        public void registryProcessor() {
            registry(ChatMsg.class, (ctx, msg) -> service.doChatForward(ctx, msg));
            registry(AckMsg.class, (ctx, msg) -> service.doSendReceiptAck(ctx, msg));
            registry(ClientMsg.class, (ctx, msg) -> service.doLogin(ctx, msg));
        }
    }


}
